<?php

namespace Biz\service\esSearch;

use Biz\model\brand\Content;
use Biz\model\brand\Content as mBrandContent;
use Doraemon\cache\ArticleCounter;
use Doraemon\cache\BlankCounter;
use Doraemon\cache\PhotoCounter;
use Doraemon\cache\Queue;
use Doraemon\cache\UserCounter;
use Doraemon\model\ArticlePhoto;
use Doraemon\service\AdmUserTag;
use Doraemon\service\Article;
use Doraemon\service\Blank;
use Doraemon\service\es\EsBrandContent;
use Doraemon\service\esSearch\Common;
use Doraemon\service\MultiContent\Schedule;
use Doraemon\service\Photos;
use Doraemon\service\User;
use Doraemon\tools\BlockType;
use Doraemon\tools\Filter;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;

class BrandContent
{

    public static function syncSave($data)
    {
        if (isset($data["data"]["id"]) && isset($data["data"]["claim_content_status"]) && isset($data["type"])) {

            if (in_array($data["type"], [Common::TYPE_ADD, Common::TYPE_UPDATE])) {
                self::_handle($data["data"]["id"]);
            }
        }
    }

    private static function _handle($priKey)
    {
        try {
            \Doraemon\model\Elasticsearch\brandContent\BrandContentEs::saveToEsById($priKey);
//            self::_updateInfo($priKey);
        } catch (\Exception $e) {
            Log::error('BrandContent-ES更新执行失败', ['id' => $priKey, 'error' => $e->getMessage()]);
        }
    }

    public static function _updateInfo($id)
    {
        if (!$id) {
            throw new \Exception('请输入id');
        }

        $brandContentInfo = Content::getById($id);

        if (!(is_array($brandContentInfo) && $brandContentInfo)) {
            throw new \Exception('品牌内容不存在id :' . $id);
        }

        $objId = $brandContentInfo["obj_id"];
        $uid = IdParse::getUid($objId);
        $userInfo = User::getBasicUserInfo($uid);
        $user_type = $userInfo['type'];
        $type = IdParse::getType($objId);

        $data = array();
        $counter = [];

        switch ($type) {
            case BlockType::TYPE_BLANK:
                $data = Blank::getBlank($objId);
                $counter = BlankCounter::getOne($objId);
                break;
            case BlockType::TYPE_ARTICLE:
                $data = Article::getArticle($objId);
                $counter = ArticleCounter::getOne($objId);
                break;
            case BlockType::TYPE_PHOTO:
            case BlockType::TYPE_ANSWER:
                $data = Photos::getPhoto($objId);
                $counter = PhotoCounter::getOne($objId);

                $remark = str_replace('#', ' ', Utils::emojiStrConvert($data['remark']));

                // 如果有点图标签，那么则加入
                $imgTag = "";
                $imgTagJson = \Doraemon\service\Photo\Schedule::getNoteImgTag($objId);
                if (Utils::extractBrandWithProductStr($imgTagJson)) {
                    $imgTagStr = Utils::extractBrandWithProductStr($imgTagJson);
                    $remark .= ' itg: ' . $imgTagStr;
                    // 点图标签
                    if (trim($imgTagStr)) {
                        $imgTag = trim($imgTagStr);
                    }
                }

                if (!(isset($data["title"]) && $data["title"])) {
                    $data['title'] = $remark;
                }

                $data['img_tag'] = $imgTag;
                $data['publish_time'] = $data["addtime"];
                break;
            default :
                throw new \Exception('没有对应处理对象');
        }

        $master_tags = AdmUserTag::getByUid($uid);

        $content_str = '';
        if ($type == BlockType::TYPE_BLANK) {
            $content_arr = json_decode($data['content_block'], 'true') ?: [];
            if ($content_arr) {
                $content_type_arr = array_filter($content_arr, function ($val) {
                    return ($val['type'] == 1 || $val['type'] == 2) ? true : false;
                }) ?: [];
                if ($content_type_arr && is_array($content_arr)) {
                    $content = array_column($content_type_arr, 'content');
                }
                if ($content && is_array($content)) {
                    $content = array_column($content, 'text');
                    $content_str = implode('', $content);
                }
            }
        } else {
            if ($type == BlockType::TYPE_PHOTO || $type == BlockType::TYPE_ANSWER) {
                $content_str = $remark;
            } else {
                $article_space_data = ArticlePhoto::getArticleSpaceInfoById($objId);
                $data['content'] = $data['description'];
                $con = '';
                if ($article_space_data && is_array($article_space_data)) {
                    foreach ($article_space_data as $val) {
                        $show_pics = json_decode($val['show_pics'], true);
                        $remark_list = array_column($show_pics, 'remark');
                        $con .= implode('', $remark_list);
                    }
                }
                $data['content'] .= $con;
                $content_str = Filter::filterContent($data['content']);

                $house_info = Article::getArticleHouseInfo($objId);

                $admin_tag_arr = array_filter(array_map('trim', explode(',', $data['admin_tag'])));
                //如果房屋面积小于 60 平米，那么自动打上小户型标签
                if ($house_info['house_size'] < 60) {
                    array_push($admin_tag_arr, '小户型');
                }

                $house_type_text = array("零", "一", "两", "三", "四", "五", "六", "七", "八", "九", "十");
                $rooms = !empty($house_info['house_construction']) ? explode(',',
                    $house_info['house_construction']) : array();
                $room = $rooms[0] ?? 0;
                $admin_tag_arr = array_filter($admin_tag_arr, function ($tag) {
                    $filter_tags = ['一室', '两室', '三室', '四室', '五室', '六室', '七室'];
                    return !in_array($tag, $filter_tags);
                });
                array_push($admin_tag_arr, $house_type_text[$room] . '室');
                $admin_tag_arr = array_unique($admin_tag_arr);
                $data['admin_tag'] = implode(',', $admin_tag_arr);
            }
        }

        $claimTime = $brandContentInfo["claim_time"] !== "0000-00-00 00:00:00" ? $brandContentInfo["claim_time"] : 0;

        $inputData = [
            'brand_uid' => (int)$brandContentInfo["brand_uid"],
            'owner_uid' => (int)$uid,
            'owner_user_type' => (int)$user_type,
            'brand_id' => (int)$brandContentInfo["brand_id"],
            'obj_type' => (int)$type,
            'obj_id' => (string)$objId,
            'is_selected' => (int)$brandContentInfo["is_selected"],
            'claim_content_status' => (int)$brandContentInfo["claim_content_status"],
            'wiki_status' => (int)$brandContentInfo["wiki_status"],
            'content_status' => (int)$brandContentInfo["content_status"],
            'match_status' => (int)$brandContentInfo["match_status"],
            'claim_time' => (int)strtotime($claimTime),
            'addtime' => (int)$data['publish_time'],
            'admin_tag' => str_replace(',', ' ', $data['admin_tag']),
            'title' => $data['title'],
            'content' => $content_str,
            'master_tag' => (string)implode(' ', $master_tags),
            'admin_score' => $data['admin_score'],
            'status' => $data['status'],
            'like' => $counter['like'],
            'share' => $counter['share'],
            'favorite' => $counter['favorite'],
            'comment' => $counter['comment'],
            'read' => $counter['read'],
            'topic_activity_id' => isset($data['topic_activity_id']) && intval($data['topic_activity_id']) ? intval($data['topic_activity_id']) : 0,
            'show_type' => isset($data['show_type']) ? intval($data['show_type']) : 0,
            'audit_status' => (int)$brandContentInfo["audit_status"],
            'claim_type' => (int)$brandContentInfo["claim_type"],
            'top_time' => (int)$brandContentInfo["top_time"],
        ];

        // 点图标签
        $inputData["img_tag"] = "";
        if (isset($data['img_tag'])) {
            $inputData["img_tag"] = $data['img_tag'];
        }

        // 关联 wiki basic title  关联 wiki basic id
        list($basicWikiTitles, $wikiBasicIds) = Schedule::getObjRelateWikiBasicTitles($id);

        if ($basicWikiTitles && $wikiBasicIds) {
            $inputData["wiki_baisc_titles"] = $basicWikiTitles;
            $inputData["wiki_baisc_ids"] = $wikiBasicIds;
        }

        // 用户粉丝数
        $userCount = UserCounter::getOne($uid);
        $inputData["fans"] = 0;
        if (isset($userCount["fans"]) && $userCount["fans"]) {
            $inputData["fans"] = $userCount["fans"];
        }

        // 是否是相似商品的内容
        $inputData["is_similar_goods"] = 0;
        if ($brandContentInfo["wiki_status"] > 0) {
            $inputData["is_similar_goods"] = 1;
        }

        // search type
        $inputData["search_type"] = "";
        if ($brandContentInfo["search_type"]) {
            $inputData["search_type"] = trim(str_replace(",", " ", $brandContentInfo["search_type"]));
        }

        // words
        $inputData["words"] = "";
        if ($brandContentInfo["words"]) {
            $wordsTmp = array();
            $wordsArr = json_decode($brandContentInfo["words"], true);
            foreach ($wordsArr as $words) {
                $wordsTmp = array_merge($wordsTmp, $words);
            }

            if (is_array($wordsTmp) && $wordsTmp) {
                $wordsTmp = array_unique($wordsTmp);
                $inputData["words"] = implode(" ", $wordsTmp);
            }
        }

        $rs = EsBrandContent::post($id, $inputData);

        if ($rs && isset($rs['code']) && $rs['code'] == 1) {
            return true;
        }

        throw new \Exception('处理失败');
    }


    // 同步更新 品牌认领信息 到内容上
    public static function syncCommunityContent($data)
    {
        if (isset($data["data"]["id"]) && isset($data["data"]["claim_content_status"]) && isset($data["type"])) {
            if ($data["type"] == Common::TYPE_UPDATE) {
                $change_field = $data["change_field"] ?: [];

                $isFieldChange = in_array('brand_id', $change_field) || in_array('claim_content_status',
                        $change_field) ||
                    in_array('audit_status', $change_field);

                if ($isFieldChange) {
                    if ($data["data"]["claim_content_status"] == mBrandContent::CLAIM_CONTENT_CANCEL && $data["data"]['top_time'] > 0) {
                        mBrandContent::update(['top_time' => 0], ['id' => $data["data"]["id"]]);
                    }
                    if (IdParse::getType($data["data"]["obj_id"]) == BlockType::TYPE_PHOTO || IdParse::getType($data["data"]["obj_id"]) == BlockType::TYPE_ANSWER) {
                        Queue::insertQueue('Photo/afterAudit', ['photo_id' => $data["data"]["obj_id"]],
                            Queue::QUEUE_ES_SYNC_COMMUNITY);
                    }

                    if (IdParse::getType($data["data"]["obj_id"]) == BlockType::TYPE_ARTICLE ||
                        IdParse::getType($data["data"]["obj_id"]) == BlockType::TYPE_BLANK || IdParse::getType($data["data"]["obj_id"]) == BlockType::TYPE_GUIDE) {
                        Queue::insertQueue('TotalArticle/updateTotalArticle', ['article_id' => $data["data"]["obj_id"]],
                            Queue::QUEUE_ES_SYNC_COMMUNITY);
                    }
                }
            }
        }
    }
}